package org.example.jvm;

import org.junit.Test;

public class StringPoolTest {

    @Test
    public void test01 () {
        String str1 = "abcd";//先检查字符串常量池中有没有"abcd"，如果字符串常量池中没有，则创建一个，然后 str1 指向字符串常量池中的对象，如果有，则直接将 str1 指向"abcd""；
        String str2 = new String("abcd");//堆中创建一个新的对象
        String str3 = new String("abcd");//堆中创建一个新的对象
        System.out.println(str1==str2);//false
        System.out.println(str2==str3);//false
    }

    @Test
    public void test02 () {
        String s1 = "计算机";
        String s2 = s1.intern();
        String s3 = "计算机";
        System.out.println(s2);//计算机
        System.out.println(s1 == s2);//true
        System.out.println(s3 == s2);//true，因为两个都是常量池中的 String 对象
    }

    @Test
    public void test03 () {
        String str1 = "str";
        String str2 = "ing";

        String str3 = "str" + "ing";//常量池中的对象
        String str4 = str1 + str2; //在堆上创建的新的对象
        String str5 = "string";//常量池中的对象
        System.out.println(str3 == str4);//false
        System.out.println(str3 == str5);//true
        System.out.println(str4 == str5);//false
    }

    @Test
    public void test04 () {
        String s1=new StringBuilder("什").append("么").toString();
// true
        System.out.println(s1==s1.intern());
        String s2=new StringBuilder("什么").toString();
// false
        System.out.println(s2==s2.intern());
    }

    @Test
    public void test05 () {
        String s1 = "Hello";
        String s2 = "Hello";
        String s3 = "Hel" + "lo";
        String s4 = "Hel" + new String("lo");
        String s5 = new String("Hello");
        String s6 = s5.intern();
        String s7 = "H";
        String s8 = "ello";
        String s9 = s7 + s8;

        System.out.println(s1 == s2);  // true
        System.out.println(s1 == s3);  // true
        System.out.println(s1 == s4);  // false
        System.out.println(s1 == s9);  // false
        System.out.println(s4 == s5);  // false
        System.out.println(s1 == s6);  // true
    }

    @Test
    public void test06 () {
        String m1 = "ja";
        String m2 = "va";
        String m = m1 + m2;
        String n = new String(new char[]{'j', 'a', 'v', 'a'});

        System.out.println(n.intern() == n);
    }
}
